package com.fingard.dsp.bank.reqrespobj.batpayrec;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.NodeSalaryItem;
import com.fingard.dsp.bank.reqrespobj.ReqRespHeader;
import com.fingard.dsp.bank.reqrespobj.RequestBase;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.ReqPayRecDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.secret.salary.DESUtil;
import com.fingard.xml.XmlReadMode;
import com.fingard.xml.XmlTextReader;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;

public class ReqBatPayRec extends RequestBase{

	public String totalNum = "";
	public String totalAmt = "";
	public String payOrganizationCode;//付方组织代码
	public String payBankLocationCode;//付方联行号
	public String smsCode="";
	public String reqBatchNO = "";//批次号，跟ATS数据库字段保持一致
	public String paySpd = "";
	public String ownAct = "";
	public String ownActName = "";
	public String ownArea = "";
	public String ownAreaName = "";
	public String ownCur = "";
	public String ownBankCode = "";
    public String oppBankCode = "";
	public String sumAccountFlag = "";
	public String abstractATS = "";
	/**代收付用途*/
	public String useType = "";
	/**描述*/
	public String memo = "";
	public String payDate = "";
	public String payTime = "";
	public String sameBnk = "";
	public String isPrivate = "";
	public String decryptKey = "";
    public String ownSwiftCode = "";
    //境外费用承担字段
    public String costMode = "";
	public boolean isNeedDecrypt = false;
	public Map<String, NodeSalaryItem> salaryItemMap;
	public String payType = "";
	//public String corpBankCode = "";-->ownBankCode
	/**是否重用批次号*/
    public String reuseSeq = "";
    public String cnapscode = "";
    /**是否为重发批次，TransType为1988-ReSend、9188-ReSend*/
    public boolean isReSend = false;

	public ReqPayRecDetail readedDetail;//复用singlepay.detail.ReqPayRecDetail
	private XmlTextReader xmlReader;
	
	public ReqBatPayRec(XmlTextReader p_xmlReader, ReqRespHeader p_header) throws Exception{
		init(p_xmlReader, p_header);
	}
	
	public ReqBatPayRec(ReqSingle p_req1908) throws Exception{
		XmlTextReader tmpReader = new XmlTextReader(p_req1908.getOriReqXml());
		ReqRespHeader tmpHeader = p_req1908.reqHeader.clone();
		init(tmpReader, tmpHeader);
		totalNum = "1";
		totalAmt = xmlReader.getSimpleText("PayAmount");
		abstractATS = xmlReader.getSimpleText("PostScript");
		reuseSeq = xmlReader.getSimpleText("ReuseSeq");
	}
	
	private void init(XmlTextReader p_xmlReader, ReqRespHeader p_header) throws Exception{
		reqHeader = p_header;
		xmlReader = p_xmlReader;
		if("1988-ReSend".equals(p_header.transType) || "9188-ReSend".equals(p_header.transType)){
			isReSend = true;
		}
		totalNum = xmlReader.getSimpleText("TotalNum");
		totalAmt = xmlReader.getSimpleText("TotalAmt");
		payOrganizationCode = xmlReader.getSimpleText("PayOrgCode");
		payBankLocationCode = xmlReader.getSimpleText("PayBankLocationCode");
		smsCode = xmlReader.getSimpleText("SmsCode");
		decryptKey =xmlReader.getSimpleText("DecryptKey");
		reqBatchNO = xmlReader.getSimpleText("ReqSeqID");//支付批号
		paySpd = xmlReader.getSimpleText("PaySpd");
		if("1988".equals(p_header.transType) || "1988-ReSend".equals(p_header.transType) || "1908".equals(p_header.transType) || "6908".equals(p_header.transType) || "9208".equals(p_header.transType) || "9288".equals(p_header.transType)){
			ownAct = xmlReader.getSimpleText("PayAct");
			ownActName = xmlReader.getSimpleText("PayName");
			ownArea = xmlReader.getSimpleText("PayArea");
			ownCur = xmlReader.getSimpleText("PayCur");
			ownBankCode = xmlReader.getSimpleText("PayBankCode");
            oppBankCode = xmlReader.getSimpleText("RecBankCode");
			ownAreaName = xmlReader.getSimpleText("PayAreaName");
            ownSwiftCode = xmlReader.getSimpleText("PaySwiftCode");
            costMode = xmlReader.getSimpleText("CostMode");
		}
		else if("9188".equals(p_header.transType) || "9188-ReSend".equals(p_header.transType) || "9108".equals(p_header.transType)){
			ownAct = xmlReader.getSimpleText("RecAct");
			ownActName = xmlReader.getSimpleText("RecName");
			ownArea = xmlReader.getSimpleText("RecArea");
			ownCur = xmlReader.getSimpleText("RecCur");
			ownBankCode = xmlReader.getSimpleText("RecBankCode");
            oppBankCode = xmlReader.getSimpleText("PayBankCode");
			ownAreaName = xmlReader.getSimpleText("RecAreaName");
		}
		sumAccountFlag = xmlReader.getSimpleText("SumAccountFlag");
		abstractATS = xmlReader.getSimpleText("ReqReserve");//对账码
		useType = xmlReader.getSimpleTextNotNull("UseType");
		if(useType.length() == 0){
			useType = xmlReader.getSimpleTextNotNull("Usage");
		}
		memo = xmlReader.getSimpleTextNotNull("Memo");
		if(memo.length() == 0){
			memo = xmlReader.getSimpleTextNotNull("Memo");
		}
		payDate = xmlReader.getSimpleText("PayDate");
    	payTime = xmlReader.getSimpleText("PayTime");
    	sameBnk = xmlReader.getSimpleText("SameBnk");
    	isPrivate = xmlReader.getSimpleText("IsPrivate");
    	if(StringHelper.isNullOrEmpty(p_header.syBank)){
    		p_header.syBank = ownBankCode;
    	}
    	if(StringHelper.isNullOrEmpty(p_header.ownAct)){
    		p_header.ownAct = ownAct;
    	}
    	payType = xmlReader.getSimpleText("PayType");
    	reuseSeq = xmlReader.getSimpleText("ReuseSeq");
    	cnapscode = xmlReader.getSimpleText("CNAPSCode");
	}

	public boolean readRecord() throws Exception{
		readedDetail = null;
		if(xmlReader.read(PATH_Detail)){
			// 是否薪资代发,PayType='F020'时为薪资代发,收方卡号、户名金额均需加解密处理
			if ("F020".equals(payType)) {
				readedDetail = new ReqPayRecDetail(xmlReader.readedXElement, reqHeader.transType,reqHeader.bankCode, payType);
			} else {
				readedDetail = new ReqPayRecDetail(xmlReader.readedXElement, reqHeader.transType,reqHeader.bankCode);
				if ((this.isNeedDecrypt) && (StringHelper.hasAnyChar(this.decryptKey))) {
					if (this.salaryItemMap.keySet().contains("PayAmount"))
					{
						NodeSalaryItem item = this.salaryItemMap.get("PayAmount");
						String plain = DESUtil.jdkDESDecryptMode(this.readedDetail.payAmount, this.decryptKey);
						if (StringHelper.isNullOrEmpty(plain)) {
							throw new Exception("解密失败");
						}
						this.readedDetail.payAmount = plain.split(item.union)[(item.index - 1)];
					}
				}
			}
			return true;
		}
		else{
			return false;
		}	
	}
	
	//是否有跨行交易
	public boolean hasOtherBank() throws Exception{
		boolean retValue = false;
		xmlReader.resetReadMode(XmlReadMode.XElementReader);
		while(xmlReader.read(PATH_Detail+"/SameBnk")){
			if(xmlReader.readedXElement.innerText.equals("0")){
				retValue = true;
				break;
			}
		}
		xmlReader.resetReadMode(XmlReadMode.XElementReader);
		return retValue;
	}

	public boolean isSameBnk()
			throws Exception
	{
		int start = 0;
		String sameBank = "";
		this.xmlReader.resetReadMode(XmlReadMode.XElementReader);
		while (this.xmlReader.read("/ATSYH/TransReq/TransParam/DetailRecord"))
		{
			start++;
			if (start == 1) {
				sameBank = this.xmlReader.readedXElement.getSingleText("SameBnk");
			} else if (!sameBank.equals(this.xmlReader.readedXElement.getSingleText("SameBnk"))) {
				throw new Exception("支付批内同时含有同行和他行的收方");
			}
		}
		this.xmlReader.resetReadMode(XmlReadMode.XElementReader);
		return "1".equals(sameBank);
	}
	
	//加急标志是否一致
	public boolean isSamePaySpd() throws Exception{
		boolean retValue = true;
		String tmpPaySpd = "";
		xmlReader.resetReadMode(XmlReadMode.XElementReader);
		while(xmlReader.read(PATH_Detail+"/PaySpd")){
			if(tmpPaySpd.length() == 0){
				tmpPaySpd = xmlReader.readedXElement.innerText;
			}
			else if(!xmlReader.readedXElement.innerText.equals(tmpPaySpd)){
				retValue = false;
				break;
			}
			
		}
		xmlReader.resetReadMode(XmlReadMode.XElementReader);
		return retValue;
	}

	//公私标志是否一致
	public boolean isSameIsPrivate() throws Exception{
		boolean retValue = true;
		String tmpIsPrivate = "";
		xmlReader.resetReadMode(XmlReadMode.XElementReader);
		while(xmlReader.read(PATH_Detail+"/IsPrivate")){
			if(tmpIsPrivate.length() == 0){
				tmpIsPrivate = xmlReader.readedXElement.innerText;
			}
			else if(!xmlReader.readedXElement.innerText.equals(tmpIsPrivate)){
				retValue = false;
				break;
			}

		}
		xmlReader.resetReadMode(XmlReadMode.XElementReader);
		return retValue;
	}
	
	public Date getPayDateOnly() throws ParseException{
    	return Format.Date10Format.parse(payDate);
    }

	public Date getPayDateTime() throws ParseException{
    	return Format.DateTimeFormat.parse(payDate + " " + payTime);
    }
	
	public int getTotalNum(){
		return Integer.parseInt(totalNum);
	}
	
	public BigDecimal getTotalAmt(){
		return new BigDecimal(totalAmt);
	}
	
	public String getOriReqXml(){
		return xmlReader.getOriXmlString();
	}
}
